<?php
namespace Home\Controller;

class PostController extends BaseController
{
    // 发帖页面
    public function index()
    {
        $this->assign('cates', M('Cate')->select());
        $this->assign('cid', I('get.cid'));
        $this->display();
    }

    // 前台：帖子列表页
    public function list()
    {
        $cid = I('get.cid');
        
        $model = M('Post'); // 实例化User对象
        $count      = $model->where(['cid'=>$cid])->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $pageHTML   = $Page->show();// 分页显示输出


 // 读取置顶的帖子
        $posts = M('post')
        ->field('bbs_post.*, bbs_member.name')
        ->join('bbs_member ON bbs_post.uid = bbs_member.id')
        ->where([
            'cid' => $cid,
            'is_top' => 1, // 筛选出不置顶的帖子
            'cid' => $cid,
            'bbs_post.status' => 1 // 正常显示的帖子
        ])
        ->order('update_time desc')
        ->select();
           // dump($posts);
         // 读取不置顶的帖子
         $posts = M('post')
         ->field('bbs_post.*, bbs_member.name')
         ->join('bbs_member ON bbs_post.uid = bbs_member.id')
         ->where([
             'cid' => $cid,
             'is_top' => 0, // 筛选出不置顶的帖子
             'bbs_post.status' => 1
         ])
         ->limit($Page->firstRow.','.$Page->listRows)
         ->order('update_time desc')
         ->select();

    $this->assign('page',$pageHTML);// 赋值分页输出
        $this->assign('topposts', $topPost);
        $this->assign('posts', $posts);
        $this->assign('cid', $cid);
        $this->display();
    }

    // 接收发帖数据
    public function add()
    {
        $userInfo = $this->checkLogin();

        $data = I('post.');
        $data['uid'] = $userInfo['id'];

        $model = D('Post');
        $res = $model->create($data);
        if($res === false) {
            $this->error($model->getError());
        } else {
            $id = $model->add();
            if($id) {
                $this->success('发帖成功', U('Post/list', ['cid'=>$data['cid']]));
            } else {
                $this->error('发帖失败');
            }
        }
    }


    //页面搜索
    public function search()
    {
        $keyword = I('get.keyword');
        $result = M('Post')
        ->join('bbs_member ON bbs_post.uid=bbs_member.id')
        ->field('bbs_post.*, bbs_member.name')
        ->where(['title'=>['LIKE', "%$keyword%"]])
        ->select();

        $this->assign('result', $result);
        $this->display();
    }
}